package com.team1.system.cipher.controller;
import java.util.Scanner;

import java.util.Random;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.io.Resources;

public class LibrarySurveyDP {
    private static final double EPSILON = 0.1; // 隐私参数，控制噪声的量

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("调查问卷：图书馆服务满意度调查\n");

        System.out.println("个人信息：");
        System.out.print("1. 性别：");
        String gender = scanner.nextLine();
        System.out.print("2. 年龄：");
        int age = Integer.parseInt(scanner.nextLine());
        System.out.print("3. 职业：");
        String occupation = scanner.nextLine();

        System.out.println("\n调查问题：");
        System.out.print("4. 您对图书馆的总体满意度如何？");
        String overallSatisfaction = scanner.nextLine();
        System.out.print("5. 您对图书馆工作人员的友好度如何？");
        String staffFriendliness = scanner.nextLine();
        System.out.print("6. 您对图书馆的图书馆藏如何？");
        String bookCollection = scanner.nextLine();
        System.out.print("7. 您对图书馆的设施如何？");
        String facilities = scanner.nextLine();
        System.out.print("8. 您对图书馆的在线服务如何？");
        String onlineServices = scanner.nextLine();

        // 添加拉普拉斯噪声保护差分隐私
        Random random = new Random();
        String noisedOverallSatisfaction = addLaplaceNoise(overallSatisfaction, random);

        System.out.println("\n感谢您的参与！您的反馈对我们改进图书馆服务非常重要。");
        System.out.println("加噪后的总体满意度：" + noisedOverallSatisfaction);

        // 将数据存入数据库
        insertSurveyData(gender, age, occupation, noisedOverallSatisfaction, staffFriendliness, bookCollection, facilities, onlineServices);

        scanner.close();
    }

    // 使用拉普拉斯机制添加噪声
    private static String addLaplaceNoise(String value, Random random) {
        double sensitivity = 1.0; // 敏感度为1，因为总体满意度范围在1-5之间
        double lambda = sensitivity / EPSILON;

        int intValue = Integer.parseInt(value);
        double noise = LaplaceMechanism(lambda, random);
        int noisedValue = intValue + (int) noise;

        // 确保添加噪声后的值仍在有效范围内
        noisedValue = Math.max(1, noisedValue);
        noisedValue = Math.min(5, noisedValue);

        return String.valueOf(noisedValue);
    }

    // 拉普拉斯机制生成噪声
    private static double LaplaceMechanism(double lambda, Random random) {
        double uniform = random.nextDouble() - 0.5;
        return -Math.signum(uniform) * lambda * Math.log(1 - 2 * Math.abs(uniform));
    }

    // 将调查数据插入数据库
    private static void insertSurveyData(String gender, int age, String occupation, String overallSatisfaction, String staffFriendliness,
                                         String bookCollection, String facilities, String onlineServices) {
        String resource = "mybatis-config.xml";
        try {
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(resource));
            try (SqlSession session = sessionFactory.openSession()) {
                LibrarySurveyMapper mapper = session.getMapper(LibrarySurveyMapper.class);

                LibrarySurveyData surveyData = new LibrarySurveyData(gender, age, occupation, overallSatisfaction, staffFriendliness,
                        bookCollection, facilities, onlineServices);

                mapper.insertSurveyData(surveyData);
                session.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


//public class LibrarySurveyController {
//    private static final String DB_URL = "jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC";
//    private static final String USER = "root";
//    private static final String PASS = "";
//    private static final String INSERT_QUERY = "INSERT INTO survey_responses (age, gender, average_visit_time, preferred_book_type) VALUES (?, ?, ?, ?)";
//
//    private double age;
//    private double gender;
//    private String averageVisitTime;
//    private String preferredBookType;
//    private final double ageSensitivity = 1;
//    private final double genderSensitivity = 1;
//    private final double privacyBudget = 1;
//
//    public LibrarySurveyController() {
//    }
//
//   //定义差分隐私参数
//    private double generateLaplaceNoise(double sensitivity, double epsilon) {
//        double scale = sensitivity / epsilon;
//        double u = Math.random() - 0.5;
//        return -scale * Math.signum(u) * Math.log(1 - 2 * Math.abs(u));
//    }
//
//    public void collectResponses() {
//        Scanner scanner = new Scanner(System.in);
//
//        System.out.println("1. 年龄：");
//        System.out.print("请输入您的年龄：");
//        int inputAge = scanner.nextInt();
//        double ageNoise = generateLaplaceNoise(ageSensitivity, privacyBudget); //添加拉普拉斯噪声
//        age = inputAge + ageNoise;
//
//        System.out.println("2. 性别：");
//        System.out.println("1. 男\n2. 女\n3. 不愿透露");
//        System.out.print("请选择一个选项（输入数字）：");
//        int inputGender = scanner.nextInt();
//        double genderNoise = generateLaplaceNoise(genderSensitivity, privacyBudget);  //添加拉普拉斯噪声
//        gender = inputGender + genderNoise;
//
//        System.out.println("3. 平均来图书馆的时间：");
//        System.out.print("请输入平均来图书馆的时间（例如：每周一次）：");
//        scanner.nextLine(); // 清除缓冲区
//        averageVisitTime = scanner.nextLine();
//
//        System.out.println("4. 来图书馆主要阅读的书籍类型：");
//        System.out.print("请输入您主要阅读的书籍类型（例如：科幻小说）：");
//        preferredBookType = scanner.nextLine();
//    }
//
//    public void saveToDatabase() {
//        try (Connection connection = DriverManager.getConnection(DB_URL, USER, PASS)) {
//            PreparedStatement preparedStatement = connection.prepareStatement(INSERT_QUERY);
//            preparedStatement.setDouble(1, age);
//            preparedStatement.setDouble(2, gender);
//            preparedStatement.setString(3, averageVisitTime);
//            preparedStatement.setString(4, preferredBookType);
//            preparedStatement.executeUpdate();
//            System.out.println("调查数据已成功保存到数据库！");
//        } catch (SQLException e) {
//            e.printStackTrace();
//            System.out.println("保存数据时出现错误。");
//        }
//    }
//
//    public static void main(String[] args) {
//        LibrarySurveyController survey = new LibrarySurveyController();
//        survey.collectResponses();
//        survey.saveToDatabase();
//    }
//}

//package com.team1.system.cipher.controller;
//
//import org.apache.ibatis.session.SqlSession;
//import org.apache.ibatis.session.SqlSessionFactory;
//import java.util.Scanner;
//
//public class LibrarySurveyController {
//    private double age;
//    private double gender;
//    private String averageVisitTime;
//    private String preferredBookType;
//    private final double ageSensitivity = 1;
//    private final double genderSensitivity = 1;
//    private final double privacyBudget = 1;
//
//    public LibrarySurveyController() {
//    }
//
//    private double generateLaplaceNoise(double sensitivity, double epsilon) {
//        double scale = sensitivity / epsilon;
//        double u = Math.random() - 0.5;
//        return -scale * Math.signum(u) * Math.log(1 - 2 * Math.abs(u));
//    }
//
//    public void collectResponses() {
//        Scanner scanner = new Scanner(System.in);
//
//        System.out.println("1. 年龄：");
//        System.out.print("请输入您的年龄：");
//        int inputAge = scanner.nextInt();
//        double ageNoise = generateLaplaceNoise(ageSensitivity, privacyBudget);
//        age = inputAge + ageNoise;
//
//        System.out.println("2. 性别：");
//        System.out.println("1. 男\n2. 女\n3. 其他\n4. 不愿透露");
//        System.out.print("请选择一个选项（输入数字）：");
//        int inputGender = scanner.nextInt();
//        double genderNoise = generateLaplaceNoise(genderSensitivity, privacyBudget);
//        gender = inputGender + genderNoise;
//
//        System.out.println("3. 平均来图书馆的时间：");
//        System.out.print("请输入平均来图书馆的时间（例如：每周一次）：");
//        scanner.nextLine(); // 清除缓冲区
//        averageVisitTime = scanner.nextLine();
//
//        System.out.println("4. 来图书馆主要阅读的书籍类型：");
//        System.out.print("请输入您主要阅读的书籍类型（例如：科幻小说）：");
//        preferredBookType = scanner.nextLine();
//    }

      //MyBatis
//    public void saveToDatabase() {
//        SqlSessionFactory sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
//        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
//            SurveyResponseMapper surveyResponseMapper = sqlSession.getMapper(SurveyResponseMapper.class);
//            SurveyResponse surveyResponse = new SurveyResponse(age, gender, averageVisitTime, preferredBookType);
//            surveyResponseMapper.insert(surveyResponse);
//            sqlSession.commit();
//            System.out.println("调查数据已成功保存到数据库！");
//        }
//    }
//
//    public static void main(String[] args) {
//        LibrarySurveyController survey = new LibrarySurveyController();
//        survey.collectResponses();
//        survey.saveToDatabase();
//    }
//}